<template>
  <div class="audio-guide-container">
    <h1 class="museum-title">语音导航</h1>

    <div class="audio-content">
      <!-- 左侧音频播放区 -->
      <div class="audio-player-container">
        <div class="player-wrapper">
          <div class="audio-player">
            <el-icon class="player-icon"><Headset /></el-icon>
            <h3>展品音频导览</h3>

            <!-- 音频播放器 -->
            <div class="player-controls">
              <audio
                ref="audioPlayer"
                class="hidden-audio"
                @timeupdate="updateProgress"
                @ended="audioEnded"
              ></audio>

              <div class="progress-bar">
                <div class="progress-bg"></div>
                <div class="progress-current" :style="{ width: progressWidth }"></div>
                <div class="time-display">
                  <span>{{ currentTime }}</span>
                  <span>{{ totalTime }}</span>
                </div>
              </div>

              <div class="control-buttons">
                <el-button circle @click="prevAudio" :disabled="!hasPrev">
                  <el-icon><Back /></el-icon>
                </el-button>
                <el-button circle class="play-button" @click="togglePlay">
                  <el-icon v-if="!isPlaying"><VideoPlay /></el-icon>
                  <el-icon v-else><VideoPause /></el-icon>
                </el-button>
                <el-button circle @click="nextAudio" :disabled="!hasNext">
                  <el-icon><Right /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 音频列表 -->
        <div class="audio-list">
          <h3>展品列表</h3>
          <el-scrollbar height="300px">
            <div
              v-for="(item, index) in audioList"
              :key="index"
              class="audio-item"
              :class="{ active: currentAudioIndex === index }"
              @click="selectAudio(index)"
            >
              <div class="item-index">{{ index + 1 }}</div>
              <div class="item-info">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-duration">{{ item.duration }}</div>
              </div>
              <el-icon v-if="currentAudioIndex === index && isPlaying"><VideoPlay /></el-icon>
              <!-- 添加删除按钮 (仅管理员可见) -->
              <el-button
                v-if="userStore.isAdmin()"
                type="danger"
                size="small"
                circle
                class="delete-button"
                @click.stop="confirmDeleteAudio(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </el-scrollbar>
        </div>

        <!-- 管理员上传音频按钮 -->
        <div v-if="userStore.isAdmin()" class="admin-controls">
          <el-upload
            class="upload-container"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAudioChange"
            accept="audio/*"
          >
            <el-button type="primary" class="upload-button">
              <el-icon><Upload /></el-icon>
              上传音频
            </el-button>
          </el-upload>
        </div>
      </div>

      <!-- 右侧展品信息展示区 -->
      <div class="exhibit-info">
        <div class="info-header">
          <h2>{{ currentAudio ? currentAudio.title : '展品介绍' }}</h2>
          <el-button
            v-if="userStore.isAdmin() && !isEditing"
            type="primary"
            @click="startEditing"
            class="edit-button"
          >
            <el-icon><Edit /></el-icon> 编辑信息
          </el-button>
        </div>

        <!-- 查看模式 -->
        <div v-if="!isEditing" class="info-content">
          <div v-if="currentAudio" class="exhibit-details">
            <div class="info-item">
              <h3>
                <el-icon><InfoFilled /></el-icon> 展品名称
              </h3>
              <p>{{ currentAudio.title }}</p>
            </div>
            <div class="info-item">
              <h3>
                <el-icon><Calendar /></el-icon> 年代
              </h3>
              <p>{{ currentAudio.era || '暂无信息' }}</p>
            </div>
            <div class="info-item">
              <h3>
                <el-icon><Document /></el-icon> 描述
              </h3>
              <p>{{ currentAudio.description || '暂无描述' }}</p>
            </div>
            <div class="info-item">
              <h3>
                <el-icon><Location /></el-icon> 位置
              </h3>
              <p>{{ currentAudio.location || '暂无位置信息' }}</p>
            </div>
          </div>
          <div v-else class="no-exhibit">
            <el-empty description="请选择一个展品以查看详细信息" />
          </div>
        </div>

        <!-- 编辑模式 (仅管理员可见) -->
        <div v-else class="edit-form">
          <el-form :model="editForm" label-position="top">
            <el-form-item label="展品名称">
              <el-input v-model="editForm.title" placeholder="请输入展品名称" />
            </el-form-item>
            <el-form-item label="年代">
              <el-input v-model="editForm.era" placeholder="请输入展品年代" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="editForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入展品描述"
              />
            </el-form-item>
            <el-form-item label="位置">
              <el-input v-model="editForm.location" placeholder="请输入展品位置" />
            </el-form-item>
            <div class="form-buttons">
              <el-button @click="cancelEditing">取消</el-button>
              <el-button type="primary" @click="saveChanges">保存</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { useAudioStore } from '../stores/audio'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Headset,
  VideoPlay,
  VideoPause,
  Back,
  Right,
  Upload,
  Edit,
  InfoFilled,
  Calendar,
  Document,
  Location,
  Delete,
} from '@element-plus/icons-vue'

// 获取用户信息存储
const userStore = useUserStore()

// 获取音频存储
const audioStore = useAudioStore()

// 音频播放器引用
const audioPlayer = ref<HTMLAudioElement | null>(null)

// 播放状态
const isPlaying = ref(false)
const currentTime = ref('00:00')
const totalTime = ref('00:00')
const progress = ref(0)

// 计算进度条宽度
const progressWidth = computed(() => `${progress.value}%`)

// 编辑状态控制
const isEditing = ref(false)

// 当前选中的音频索引
const currentAudioIndex = ref(-1)

// 使用Pinia store中的音频列表
const audioList = computed(() => audioStore.audioList)

// 当前选中的音频
const currentAudio = computed(() => {
  if (currentAudioIndex.value >= 0 && currentAudioIndex.value < audioList.value.length) {
    return audioList.value[currentAudioIndex.value]
  }
  return null
})

// 是否有上一个/下一个音频
const hasPrev = computed(() => currentAudioIndex.value > 0)
const hasNext = computed(() => currentAudioIndex.value < audioList.value.length - 1)

// 编辑表单数据
const editForm = reactive({
  title: '',
  era: '',
  description: '',
  location: '',
})

// 选择音频
const selectAudio = (index: number) => {
  currentAudioIndex.value = index
  // 加载对应的音频文件
  if (audioPlayer.value && audioList.value[index].src) {
    audioPlayer.value.src = audioList.value[index].src
    // 重置播放器状态
    audioPlayer.value.load() // 添加这一行确保音频被正确加载
  }
  isPlaying.value = false
  progress.value = 0
  currentTime.value = '00:00'
  totalTime.value = audioList.value[index].duration
}

// 播放/暂停切换
const togglePlay = () => {
  if (currentAudioIndex.value === -1 && audioList.value.length > 0) {
    // 如果没有选中音频，默认选择第一个
    selectAudio(0)
  }

  if (audioPlayer.value) {
    if (isPlaying.value) {
      audioPlayer.value.pause()
    } else {
      audioPlayer.value.play().catch((error) => {
        // 处理播放错误，例如没有音频源
        ElMessage.error('无法播放音频，请确保已上传音频文件')
        console.error('播放错误:', error)
      })
    }
    isPlaying.value = !isPlaying.value
  }
}

// 上一个音频
const prevAudio = () => {
  if (hasPrev.value) {
    selectAudio(currentAudioIndex.value - 1)
  }
}

// 下一个音频
const nextAudio = () => {
  if (hasNext.value) {
    selectAudio(currentAudioIndex.value + 1)
  }
}

// 更新进度条
const updateProgress = () => {
  if (audioPlayer.value) {
    const current = audioPlayer.value.currentTime
    const total = audioPlayer.value.duration

    if (!isNaN(total) && total > 0) {
      progress.value = (current / total) * 100
      currentTime.value = formatTime(current)
      totalTime.value = formatTime(total)
    }
  }
}

// 音频播放结束
const audioEnded = () => {
  isPlaying.value = false
  progress.value = 0
  currentTime.value = '00:00'

  // 自动播放下一个
  if (hasNext.value) {
    nextAudio()
    togglePlay()
  }
}

// 格式化时间 (秒 -> MM:SS)
const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 开始编辑
const startEditing = () => {
  if (currentAudio.value) {
    // 复制当前数据到编辑表单
    editForm.title = currentAudio.value.title
    editForm.era = currentAudio.value.era || ''
    editForm.description = currentAudio.value.description || ''
    editForm.location = currentAudio.value.location || ''
    isEditing.value = true
  } else {
    ElMessage.warning('请先选择一个展品')
  }
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
}

// 保存更改
const saveChanges = () => {
  if (currentAudioIndex.value >= 0) {
    // 更新Pinia store中的数据
    audioStore.updateAudio(currentAudioIndex.value, {
      title: editForm.title,
      era: editForm.era,
      description: editForm.description,
      location: editForm.location,
    })
    isEditing.value = false
    ElMessage.success('展品信息已更新')
  }
}

// 处理音频上传
const handleAudioChange = (file: any) => {
  if (!file) return

  // 检查文件类型
  const isAudio = file.raw.type.startsWith('audio/')
  if (!isAudio) {
    ElMessage.error('请上传音频文件!')
    return
  }

  // 检查文件大小 (限制为10MB)
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('音频大小不能超过10MB!')
    return
  }

  // 这里应该处理音频文件上传
  // 在实际应用中，应该将文件上传到服务器并获取URL
  // 这里仅作为示例，创建一个本地URL
  const audioUrl = URL.createObjectURL(file.raw)

  // 创建一个新的音频项
  const newAudio = {
    id: audioList.value.length + 1,
    title: file.name.replace(/\.[^/.]+$/, ''), // 移除文件扩展名作为标题
    src: audioUrl,
    duration: '00:00', // 实际应用中应该获取真实时长
    era: '',
    description: '',
    location: '',
  }

  // 添加到Pinia store
  audioStore.addAudio(newAudio)
  ElMessage.success('音频上传成功')

  // 选择新上传的音频
  selectAudio(audioList.value.length - 1)
}
// 确认删除音频
const confirmDeleteAudio = (index: number) => {
  ElMessageBox.confirm('确定要删除这个音频吗？此操作不可恢复。', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteAudio(index)
    })
    .catch(() => {
      // 用户取消删除操作
    })
}

// 删除音频
const deleteAudio = (index: number) => {
  // 如果正在播放的是要删除的音频，先停止播放
  if (currentAudioIndex.value === index && isPlaying.value) {
    if (audioPlayer.value) {
      audioPlayer.value.pause()
      isPlaying.value = false
    }
  }

  // 从Pinia store中删除
  audioStore.deleteAudio(index)

  // 更新当前选中的索引
  if (audioList.value.length === 0) {
    // 如果删除后列表为空
    currentAudioIndex.value = -1
  } else if (currentAudioIndex.value >= index) {
    // 如果删除的是当前选中的或之前的音频，需要调整索引
    currentAudioIndex.value = Math.max(0, currentAudioIndex.value - 1)
  }

  ElMessage.success('音频已删除')
}
// 组件挂载时
onMounted(() => {
  // 如果有音频列表，默认选择第一个
  if (audioList.value.length > 0) {
    selectAudio(0)
  }
})
</script>

<style lang="scss" scoped>
.audio-guide-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去导航栏的高度 */
  width: 100%;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
  background-image:
    radial-gradient(circle at 25px 25px, rgba(139, 90, 43, 0.2) 2%, transparent 0%),
    radial-gradient(circle at 75px 75px, rgba(139, 90, 43, 0.2) 2%, transparent 0%);
  background-size: 100px 100px;
}

.museum-title {
  color: #8b5a2b;
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
  font-family: 'SimSun', serif;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.audio-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;

  @media (min-width: 768px) {
    flex-direction: row;
    align-items: flex-start;
  }
}

.audio-player-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e0d5;
}

.player-wrapper {
  margin-bottom: 20px;
}

.audio-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f6f2;
  border: 1px solid #e8e0d5;

  h3 {
    color: #8b5a2b;
    margin: 10px 0 20px;
    font-family: 'SimSun', serif;
  }

  .player-icon {
    font-size: 40px;
    color: #8b5a2b;
    margin-bottom: 10px;
  }
}

.hidden-audio {
  display: none;
}

.player-controls {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.progress-bar {
  position: relative;
  width: 100%;
  height: 6px;
  background-color: #e8e0d5;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;

  .progress-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #e8e0d5;
  }

  .progress-current {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    background-color: #8b5a2b;
    transition: width 0.1s linear;
  }

  .time-display {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    font-size: 12px;
    color: #8b5a2b;
  }
}

.control-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;

  .el-button {
    color: #8b5a2b;
    border-color: #e8e0d5;

    &:hover {
      color: #6d4522;
      border-color: #d3c6b0;
    }

    &.play-button {
      width: 50px;
      height: 50px;
      font-size: 20px;
      background-color: #f0e6d9;

      &:hover {
        background-color: #e8e0d5;
      }
    }
  }
}

.audio-list {
  margin-top: 20px;

  h3 {
    color: #8b5a2b;
    margin-bottom: 15px;
    font-family: 'SimSun', serif;
    padding-left: 10px;
    border-left: 3px solid #8b5a2b;
  }

  .audio-item {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    border-radius: 6px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: background-color 0.2s;
    position: relative;

    &:hover {
      background-color: #f9f6f2;

      .delete-button {
        opacity: 1;
      }
    }

    &.active {
      background-color: #f0e6d9;
      border-left: 3px solid #8b5a2b;
    }

    .delete-button {
      opacity: 0;
      transition: opacity 0.2s;
      margin-left: 8px;

      &:hover {
        background-color: #f56c6c;
        color: white;
      }
    }
    .item-index {
      width: 24px;
      height: 24px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #8b5a2b;
      color: white;
      border-radius: 50%;
      font-size: 12px;
      margin-right: 12px;
    }

    .item-info {
      flex: 1;

      .item-title {
        font-weight: 500;
        color: #5d4037;
        margin-bottom: 4px;
      }

      .item-duration {
        font-size: 12px;
        color: #8d6e63;
      }
    }

    .el-icon {
      color: #8b5a2b;
      font-size: 16px;
    }
  }
}

.admin-controls {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;

  .upload-button {
    background-color: #8b5a2b;
    border-color: #8b5a2b;

    &:hover {
      background-color: #6d4522;
      border-color: #6d4522;
    }
  }
}

.exhibit-info {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e0d5;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #f0e6d9;
  padding-bottom: 10px;

  h2 {
    color: #8b5a2b;
    font-size: 22px;
    margin: 0;
    font-family: 'SimSun', serif;
  }

  .edit-button {
    background-color: #8b5a2b;
    border-color: #8b5a2b;

    &:hover {
      background-color: #6d4522;
      border-color: #6d4522;
    }
  }
}

.info-content {
  .info-item {
    margin-bottom: 20px;

    h3 {
      color: #8b5a2b;
      font-size: 18px;
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
      font-family: 'SimSun', serif;
    }

    p {
      color: #333;
      line-height: 1.6;
      margin: 0;
      text-align: justify;
      padding-left: 26px;
    }
  }
}

.no-exhibit {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #8d6e63;
}

.edit-form {
  .el-form-item {
    margin-bottom: 15px;
  }

  .form-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }
}
</style>

